import React, { PureComponent } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import * as Utils from '@/utils/utils';
import AccountJS from '@/utils/account';
import Enumerable from 'linq';
import moment from 'moment';

import {
  Row,
  Col,
  Card,
  Table,
  Form,
  Button,
  Input,
  Icon,
  Select,
  DatePicker,
  Alert,
  Menu,
} from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './styles.less';

const { Item: FormItem } = Form;
const { Option } = Select;
const { RangePicker, MonthPicker } = DatePicker;

const ModelName = 'boxCount';

@connect(({ boxCount, loading }) => ({
  loading: loading.models[ModelName],
  model: boxCount,
}))
@Form.create()
class Comp extends PureComponent {
  state = {};

  componentDidMount() {
    this.doQuery();
  }

  doQuery(cond) {
    const { dispatch, model } = this.props;
    let payload = {
      ...model.qc,
      ...cond,
    };
    dispatch({
      type: `${ModelName}/get`,
      payload: payload,
    });
  }

  handlePageChange = (number, size) => {
    const cond = {
      pageSize: size,
      pageNumber: number,
    };
    this.doQuery(cond);
  };

  handleSearch = e => {
    e.preventDefault();

    const { form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.log('FV', fieldsValue);

      let payload = {
        ...fieldsValue,
        year: fieldsValue.yearMonth ? fieldsValue.yearMonth.year() : 0,
        month: fieldsValue.yearMonth ? fieldsValue.yearMonth.month() + 1 : 0,
        lockDateStart:
          fieldsValue.lockDate &&
            Array.isArray(fieldsValue.lockDate) &&
            fieldsValue.lockDate.length === 2
            ? Utils.getChineseDate(fieldsValue.lockDate[0])
            : null,
        lockDateEnd:
          fieldsValue.lockDate &&
            Array.isArray(fieldsValue.lockDate) &&
            fieldsValue.lockDate.length === 2
            ? Utils.getChineseDate(fieldsValue.lockDate[1])
            : null,
      };
      delete payload.yearMonth;
      delete payload.lockDate;
      this.doQuery(payload);
    });
  };

  handleFormReset = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.resetFields();

    dispatch({
      type: `${ModelName}/reSetQC`,
    });
  };

  queryForm = () => {
    const {
      form: { getFieldDecorator },
      model,
    } = this.props;

    const { qc } = model;

    const colSpanLayout = {
      xs: 24,
      md: 12,
      lg: 5,
    };

    const formLayout = {
      labelCol: {
        xs: { span: 7 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 17 },
        sm: { span: 17 },
      },
    };

    return (
      <Form onSubmit={this.handleSearch}>
        <Row gutter={1} className={styles.dataRow}>
          <Col {...colSpanLayout}>
            <FormItem label="关键字" {...formLayout}>
              {getFieldDecorator('keyword', {
                initialValue: qc.keyword,
              })(<Input placeholder="姓名、单号、SO号、金额" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="年月" {...formLayout}>
              {getFieldDecorator('yearMonth', {
                initialValue:
                  qc.year && qc.year > 0 && qc.month && qc.month > 0
                    ? moment(`${qc.year}-${qc.month}`)
                    : null,
              })(<MonthPicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="核销日期" {...formLayout}>
              {getFieldDecorator('lockDate', {
                initialValue:
                  qc.lockDateStart && qc.lockDateEnd
                    ? [moment(qc.lockDateStart), moment(qc.lockDateEnd)]
                    : null,
              })(<RangePicker />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="主单核销" {...formLayout}>
              {getFieldDecorator('isLock', {
                initialValue: qc.isLock
              })(
                <Select placeholder="请选择">
                  <Option value={-1}>全部</Option>
                  <Option value={0}>未核销</Option>
                  <Option value={1}>已核销</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={3} style={{ float: 'right' }} >
            <div>
              <Button type="primary" htmlType="submit">
                查询
            </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
            </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  summary(data) {
    return data.tag && (
      <Alert
        showIcon type="info"
        message={<span>总计柜量({data.totalCount})：{data.tag.map(item => <span style={{ marginLeft: '2em' }} key={item.boxType}>{item.boxType}*{item.boxCount}</span>)}</span>}
      />
    );
  }

  render() {
    const { model, loading } = this.props;
    const { data } = model;

    const columns = [
      {
        title: '#',
        dataIndex: 'ReNo',
        // width: '30',
        // fixed: 'left',        
        render: (text, record, index) => (
          <span> {index + 1 + (data.currentPage - 1) * data.pageSize} </span>
        ),
      },
      {
        title: '柜号',
        // width: '100',
        // fixed: 'left',
        dataIndex: 'objectNumber',
      },
      {
        title: '封条号',
        dataIndex: 'sealNumber',
        // width: '100',
        // fixed: 'left',
      },
      {
        title: '业务员',
        dataIndex: 'salerName',
      },
      {
        title: '年月',
        dataIndex: 'yearMonth',
        render: (text, record) => (
          <span>
            {record.year}-{record.month}
          </span>
        ),
      },
      {
        title: '单号',
        dataIndex: 'billNumber',
        render: text => <Link to={`/Bill/${text}/hbl`}>{text}</Link>,
      },
      {
        title: 'SO号',
        dataIndex: 'so',
      },
      {
        title: '主单核销',
        dataIndex: 'lockDate',
        render: (text, record) => Utils.getChineseDate(record.lockDate, '未核销'),
      },

      { title: '柜型', dataIndex: 'boxTypeName', },
      { title: '起运港', dataIndex: 'sourcePort', },
      { title: '目的港', dataIndex: 'targetPort', },
      { title: '船名/航次', dataIndex: 'shipName', },
      { title: '开船日期', dataIndex: 'etd', render: (text, record) => <span>{Utils.getChineseDate(text)}</span>, },
    ];

    return (
      <PageHeaderWrapper>
        <div className={styles.tableListForm}>{this.queryForm()}</div>
        <Card bordered={false}>
          {data && this.summary(data)}
          <Table
            style={{ marginTop: '12px' }}
            // scroll={{ x: 1300 }}
            rowKey={record => record.objectNumber}
            size="small"
            loading={loading}
            dataSource={data.dataList}
            columns={columns}
            pagination={{
              showSizeChanger: true,
              total: data.totalCount,
              pageSize: data.pageSize,
              current: data.currentPage,
              onChange: this.handlePageChange,
              onShowSizeChange: this.handlePageChange,
              showTotal: (total, range) => `共${total}项，当前显示 ${range[0]}-${range[1]}`,
            }}
          // footer={() => footerContent()}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Comp;
